import type { LoginFormRaw } from '@/types/sys/auth';
import { defineStore } from 'pinia';

interface UserInfo {
  id: string;
  name: string;
  avatar: string;
  roles: string[];
  permissions: string[];
}

export const useUserStore = defineStore('user', () => {
  const user = reactive<UserInfo>({
    id: '',
    name: '',
    avatar: '',
    roles: [],
    permissions: []
  });

  const login = async (data: LoginFormRaw) => {
    const res = await loginApi(data);
    // 设置token
    setToken(res.token);
  };

  const getUserInfo = async () => {
    const res = await getUserInfoApi();
    const { id, name, avatar, roles, permissions } = res;
    user.id = id;
    user.name = name;
    user.avatar = avatar;
    // 没有角色，则使用默认角色
    user.roles = roles || ['ROLE_DEFAULT'];
    user.permissions = permissions;
  };

  const logout = () => {
    user.id = '';
    user.name = '';
    user.avatar = '';
    user.roles = [];
    user.permissions = [];
    removeToken();
  };

  return { ...toRefs(user), login, getUserInfo, logout };
});
